import servce from '../msg/service';

interface IError {
	code?: number;
	error?: string;
}

export interface IRole {
	_id: string;
	role_no: string;
	role_name: string;
	pk_val: string;
	role_type_id: string;
	role_type_name: string;
}

export interface IMenu {
	_id: string;
	menu_no: string;
	menu_name: string;
	client_type: string;
	parent_no: string;
	icon: string;
	show_type: string;
	description: string;
	priority: number;
	is_single: boolean;
	is_offline: boolean;
	is_guest: boolean;
	productid: string;
	systemid: string;
	formid: string;
	background: string;
	refsystemid: string;
	formname: string;
	package_no: string;
	package_name: string;
	package_url: string;
	auth_code: number;
}

export interface IUserRoleAndAuthInfo {
	roles: IRole[];
	menus: IMenu[];
	role_no: string;
	usercode: string;
	params?: any;	// todo need fixed
}

export const PREFIX_ROLES = 'ROLE_';

async function _get_user_info(productid: string, role_no?: string) {
	// var pages = getCurrentPages() // 获取加载的页面
	// var currentPage = pages[pages.length-1] // 获取当前页面的对象
	// var url = currentPage.route // 当前页面url
	const params = {
		clienttype: '9',
		productid,
		role_no,
		systemid: '12'
	};
	const ret = await servce<IUserRoleAndAuthInfo>('permservice.getuserroleandauthinfo', params);
	const err = ret as IError;
	if ((err.code === undefined) && (err.error === undefined)) {
		const data = ret as IUserRoleAndAuthInfo;
		wx.setStorageSync('authorization-info', data);
		return data;
	} else {
		console.error(err);
		throw new Error('Could not get user auth info:' + err.error);
	}
}

export async function get_user_info(productid: string, cacha: boolean, role_no?: string) {
	if (cacha) {
		const ui = wx.getStorageSync('authorization-info') as IUserRoleAndAuthInfo;
		if (ui && (!role_no || ui.role_no === role_no)) {
			return ui;
		} else {
			return await _get_user_info(productid, role_no);
		}
	} else {
		return await _get_user_info(productid, role_no);
	}
}
